<template>
  <div >
    <div v-if="isTijiShow" class="measure-tools">
      <div class="title">
        <span>测量工具箱</span>
        <i class="el-icon-close" @click="close" id="close-1"></i>
      </div>
      <div class="measure">
        <div class="measure-item" @click="getPosition">
          <i class="iconfont icon-31dingwei" id="measure-icon"></i>
          <span>位置测量</span>
        </div>
        <div class="measure-item" @click="getDistance">
          <i class="iconfont icon-celiang" id="measure-icon"></i>
          <span>长度测量</span>
        </div>
        <div class="measure-item" @click="getArea">
          <i class="iconfont icon-mianjiceliang" id="measure-icon"></i>
          <span>面积测量</span>
        </div>
        <div class="measure-item" @click="getHeight">
          <i class="iconfont icon-diaogougaodu-xian" id="measure-icon"></i>
          <span>高度测量</span>
        </div>
        <div class="measure-item" @click="showTiji">
          <i class="iconfont icon-tijikongjian-xianxing" id="measure-icon"></i>
          <span>体积测量</span>
        </div>
        <div class="measure-item" @click="clearAll">
          <i class="el-icon-scissors" id="measure-icon"></i>
          <span>清除所有</span>
        </div>
      </div>
    </div>
    <!-- 挖方计算 -->
    <div class="measure-tiji" v-if="tiji">
      <div class="tiji-top">
        <span>挖方体积计算</span>
        <i class="el-icon-close" @click="closeTiji" id="close-2"></i>
      </div>
      <div class="tiji-bottom">
        <div class="tiji-deep">挖方深度：<input type="text" class="input-tiji" v-model="deep"> m</div>
        <div class="tiji-draw" @click="drawTiji">
          <i class="el-icon-edit"></i>
          <span> 绘制区域</span>
        </div>
        <div class="measure-item" @click="clearAll">
          <i class="el-icon-scissors" id="measure-icon"></i>
          <span>清除所有</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import global from '@/views/Global.vue'
export default {
  props:['hideMeasureTools'],
  data() {
    return {
      // label坐标点
      coordinate:{},
      // 测高数据
      lon:null,
      lat:null,
      MouseHeight:null,
      ray:null,
      position1:null,
      feature:null,
      cartographic1:null,
      // 测体积组件使用时工具箱不显示
      isTijiShow:true,
      tiji:false,
      deep:0,
    }
  },
  mounted() {
  },
  methods: {
    close(){
      const viewer = global.viewer
      viewer.entities.removeAll()
      this.$emit('hideMeasureTools')
    },
    // 获取坐标
    getPosition(e){
      const _this= this
      const viewer = global.viewer
      let phandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      viewer.phandler = phandler
      phandler.setInputAction(function(event){
          let ray = viewer.camera.getPickRay(event.position);
          let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
          let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
          let alt = cartographic.height; // 高度
          let coordinate = {
              longitude: Number(lng.toFixed(6)),
              latitude: Number(lat.toFixed(6)),
              altitude: Number(alt.toFixed(2))
          };
          let label1 = viewer.entities.add({
            position:Cesium.Cartesian3.fromDegrees(coordinate.longitude,coordinate.latitude,coordinate.altitude),
            label: {
                text: '经度：'+coordinate.longitude+'\n纬度：'+coordinate.latitude+'\n高程：'+coordinate.altitude,
                scale: 0.7,
                style:Cesium.LabelStyle.FILL_AND_OUTLINE,
                fillColor:Cesium.Color.WHITE,
                showBackground:false,
                pixelOffset:new Cesium.Cartesian2(0,-80),
            }
          })
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
      phandler.setInputAction((event) => {
        // 取消鼠标移动监听
        phandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 清除所有事件
        if (phandler) {
          phandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
          phandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
          phandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    // 获取距离
    getDistance(){
      const viewer = global.viewer
      // 取消双击事件-追踪该位置
      var lhandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      viewer.lhandler = lhandler
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      var positions = [];
      var poly = null;
      // var tooltip = document.getElementById("toolTip");
      var distance = 0;
      var cartesian = null;
      var floatingPoint;
      // tooltip.style.display = "block";
      lhandler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(positions);
          } else {
            positions.pop();
            positions.push(cartesian);
          }
          distance = getSpaceDistance(positions);
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      lhandler.setInputAction(function (movement) {
          let ray = viewer.camera.getPickRay(movement.position);
          cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          if (positions.length == 0) {
            positions.push(cartesian.clone());
          }
          positions.push(cartesian);
          //在三维场景中添加Label
          var textDisance = distance + "米";
          floatingPoint = viewer.entities.add({
            name: '空间直线距离',
            position: positions[positions.length - 1],
            point: {
              pixelSize: 5,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
            },
            label: {
              text: textDisance,
              font: '18px sans-serif',
              fillColor: Cesium.Color.GOLD,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineWidth: 2,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(20, -20),
            }
          });
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      lhandler.setInputAction(function (movement) {
        lhandler.destroy(); //关闭事件句柄
        positions.pop(); //最后一个点无效
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      var PolyLinePrimitive = (function () {
        function _(positions) {
          this.options = {
            name: '直线',
            polyline: {
              show: true,
              positions: [],
              material: Cesium.Color.CHARTREUSE,
              width: 10,
              clampToGround: true
            }
          };
            this.positions = positions;
            this._init();
        }
        _.prototype._init = function () {
          var _self = this;
          var _update = function () {
            return _self.positions;
          };
          //实时更新polyline.positions
          this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
          viewer.entities.add(this.options);
        };
        return _;
      })();
      //空间两点距离计算函数
      function getSpaceDistance(positions) {
        var distance = 0;
        for (var i = 0; i < positions.length - 1; i++) {
          var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
          var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
          /**根据经纬度计算出距离**/
          var geodesic = new Cesium.EllipsoidGeodesic();
          geodesic.setEndPoints(point1cartographic, point2cartographic);
          var s = geodesic.surfaceDistance;
          //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
          //返回两点之间的距离
          s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
          distance = distance + s;
        }
        return distance.toFixed(2);
      }
    },
    // 获取面积
    getArea(){
      const viewer = global.viewer
      this.$message('单击左键绘制范围，右键结束')
      const _this = this
      var ahandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      viewer.ahandler = ahandler
      // 取消双击事件-追踪该位置
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      // 鼠标事件
      ahandler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
      )
      var positions = []
      var tempPoints = []
      var polygon = null
      var cartesian = null
      var floatingPoint
      var measureFeature_polygon = []
      var adapCoordi = []
      var maxHeight = []
      var getHei=[]
 
      ahandler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.endPosition)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
 
      ahandler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.position)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        // positions.pop();
        positions.push(cartesian)
        // 在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
          positions[positions.length - 1]
        )
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
        var heightString = cartographic.height
        tempPoints.push({
          lon:longitudeString,
          lat:latitudeString,
          hei:heightString
        })
        adapCoordi.push(longitudeString,latitudeString,0)
        getHei.push(longitudeString,latitudeString,heightString)
        // 汇总所有高程
        maxHeight.push(heightString)
        adapCoordi=adapCoordi
        maxHeight=maxHeight
        _this.tempPoints=tempPoints
        getHei=getHei
        // tempPoints.push(longitudeString)
        // tempPoints.push(latitudeString)
        // getHight(tempPoints)
        floatingPoint = viewer.entities.add({
          name: '多边形面积',
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.DEEPSKYBLUE,
            outlineWidth: 3
          }
        })
        measureFeature_polygon.push(  )
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
 
      ahandler.setInputAction(function (movement) {
        ahandler.destroy()
        positions.pop()
        var polyCenter = Cesium.BoundingSphere.fromPoints(positions).center
        var textArea = getArea(tempPoints) + 'km²'
        const _label = viewer.entities.add({
          name: '多边形面积',
          position: polyCenter,
          // position: positions[positions.length - 1],
          label: {
            text: textArea,
            font: '16px sans-serif',
            fillColor: Cesium.Color.DARKORANGE,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        measureFeature_polygon.push(_label)
        // 绘制范围按钮颜色变回默认

        _this.isChange3=false
        let floodArr = []
        tempPoints.forEach((item)=>{
          floodArr.push(item.hei)
        })
        floodArr.sort()
        // 求最大高程
        let targetHeight=floodArr[floodArr.length-1].toFixed(2)-0
        // 求最小高程
        let minFlood=floodArr[0].toFixed(2)-0
        _this.maxFlood=targetHeight
        _this.miniFlood=minFlood
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
 
      var radiansPerDegree = Math.PI / 180.0 // 角度转化为弧度(rad)
      var degreesPerRadian = 180.0 / Math.PI // 弧度转化为角度
 
      // 计算多边形面积
      function getArea(points) {
        var res = 0
        // 拆分三角曲面
        for (var i = 0; i < points.length - 2; i++) {
          var j = (i + 1) % points.length
          var k = (i + 2) % points.length
          var totalAngle = Angle(points[i], points[j], points[k])
 
          var dis_temp1 = distance(positions[i], positions[j])
          var dis_temp2 = distance(positions[j], positions[k])
          res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle))
          console.log(res)
        }
 
        return (res / 1000000.0).toFixed(4)
      }
      function logPosition (position) {
        var ray = viewer.camera.getPickRay(position)
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian)
        var long2 = Cesium.Math.toDegrees(cartographic.longitude)
        var lat2 = Cesium.Math.toDegrees(cartographic.latitude)
        console.log(long2 + ',' + lat2)
      }
 
      /* 角度 */
      function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1)
        var bearing23 = Bearing(p2, p3)
        var angle = bearing21 - bearing23
        if (angle < 0) {
          angle += 360
        }
        return angle
      }
      /* 方向 */
      function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree
        var lon1 = from.lon * radiansPerDegree
        var lat2 = to.lat * radiansPerDegree
        var lon2 = to.lon * radiansPerDegree
        var angle = -Math.atan2(
          Math.sin(lon1 - lon2) * Math.cos(lat2),
          Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        )
        if (angle < 0) {
          angle += Math.PI * 2.0
        }
        angle = angle * degreesPerRadian // 角度
        return angle
      }
 
      var PolygonPrimitive = (function () {
        function _(positions) {
          this.options = {
            name: '多边形',
            polygon: {
              hierarchy: [],
              // perPositionHeight : true,
              material: new Cesium.Color(0, 124 / 255, 247 / 255, 0.2)
              // material: Cesium.Color.GREEN.withAlpha(0.5)
              // heightReference:20000
            }
          }
 
          this.hierarchy = { positions }
          this._init()
        }
 
        _.prototype._init = function () {
          var _self = this
          var _update = function () {
            return _self.hierarchy
          }
          // 实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new Cesium.CallbackProperty(
            _update,
            false
          )
          const _polygon = viewer.entities.add(this.options)
          _polygon=_polygon
          measureFeature_polygon.push(_polygon)
          this.measureFeature_polygon=measureFeature_polygon
          // console.log(this.measureFeature_polygon);
        }
 
        return _
      })()
 
      function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1)
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2)
        /** 根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic()
        geodesic.setEndPoints(point1cartographic, point2cartographic)
        var s = geodesic.surfaceDistance
        // 返回两点之间的距离
        s = Math.sqrt(
          Math.pow(s, 2) +
            Math.pow(point2cartographic.height - point1cartographic.height, 2)
        )
        return s
      }
    },
    // 获取垂直高度
    getHeight(){
      const viewer = global.viewer
      this.$message('单击左键选择位置')
      const _this = this;
      // 存储点
      const positions = []
      // 存储标签
      let label = null
      const hhandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      // 注册鼠标左击事件
      hhandler.setInputAction(evt => {
        var cartesian = viewer.scene.pickPosition(evt.position);
        if (!cartesian) return
        positions.push(cartesian.clone())
        if (positions.length >= 2) {
          hhandler.destroy()
          label = _this.addLabel(positions[0], _this.getLength(positions))
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
      hhandler.setInputAction(evt => {
        var cartesian = viewer.scene.pickPosition(evt.endPosition);
        if (!cartesian) return
        if (positions.length >= 2) {
          positions.pop()
          positions.push(cartesian.clone())
        } else if (positions.length === 1) {
          positions.push(cartesian.clone())
          _this.addLine(positions)
        }
        if (label) {
          label.label.text.setValue(_this.getLength(positions))
          label.position.setValue(positions[1])
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      hhandler.setInputAction(evt => {
        hhandler.destroy()
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      console.log(positions);
    },
    addLine(positions) {
      const viewer = global.viewer
      viewer.entities.add(
        new Cesium.Entity({
          polyline: {
            positions: new Cesium.CallbackProperty(() => positions, false),
            width: 2,
            material: Cesium.Color.YELLOW,
            clampToGround: true,
          }
        })
      )
    },
    addLabel(point, text) {
      const viewer = global.viewer
      return viewer.entities.add(
        new Cesium.Entity({
            position: point,
            label: {
              text: '两点高差为'+text+'m',
              font: '14px sans-serif',
              style: Cesium.LabelStyle.FILL_AND_OUTLINE, //FILL  FILL_AND_OUTLINE OUTLINE
              fillColor: Cesium.Color.YELLOW,
              showBackground: true, //指定标签后面背景的可见性
              backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.8), // 背景颜色
              backgroundPadding: new Cesium.Cartesian2(6, 6), //指定以像素为单位的水平和垂直背景填充padding
              pixelOffset: new Cesium.Cartesian2(0, -25),
              disableDepthTestDistance: Number.POSITIVE_INFINITY
            }
        })
      )
    },
    getLength(points) {
      let point1 =Cesium.Cartographic.fromCartesian(points[0])
      let point2 =Cesium.Cartographic.fromCartesian(points[1])
      let hei1=point1.height
      let hei2=point2.height
      let height = 0
      if(hei1>hei2){
        height=hei1-hei2
      }else{
        height=hei2-hei1
      }
      height=height.toFixed(2)
      console.log(height);
      return height
    },
    showTiji(){
      this.isTijiShow=false
      this.tiji=true
    },
    getVolume(){

    },
    clearAll(){
      const viewer = global.viewer
      viewer.entities.removeAll()
      this.$emit('hideMeasureTools')
      viewer.phandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      viewer.phandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      viewer.phandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      viewer.lhandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      viewer.lhandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      viewer.lhandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      viewer.ahandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      viewer.ahandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      viewer.ahandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);


      viewer.hhandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      viewer.hhandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      viewer.hhandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      viewer.phandler.destroy()
      viewer.lhandler.destroy()
      viewer.ahandler.destroy()
      viewer.hhandler.destroy()
      // handler.removeInputAction(viewer.phandler);
      // handler.removeInputAction(viewer.lhandler);
      // handler.removeInputAction(viewer.ahandler);
      // handler.removeInputAction(viewer.hhandler);
      this.deep=0
    },
    // 关闭体积测量
    closeTiji(){
      this.tiji=false
      this.isTijiShow=true
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    },
    drawTiji(){
      const viewer = global.viewer
      this.$message('单击左键绘制范围，右键结束')
      if(this.deep===0){
        this.$message('挖土深度不可为0')
        return
      }
      const _this = this
      var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      // 取消双击事件-追踪该位置
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
      // 鼠标事件
      handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
      )
      var positions = []
      var tempPoints = []
      var polygon = null
      var cartesian = null
      var floatingPoint
      var measureFeature_polygon = []
      var adapCoordi = []
      var maxHeight = []
      var getHei=[]
 
      handler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.endPosition)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
        if (positions.length >= 2) {
          if (!Cesium.defined(polygon)) {
            polygon = new PolygonPrimitive(positions)
          } else {
            positions.pop()
            positions.push(cartesian)
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
 
      handler.setInputAction(function (movement) {
        const ray = viewer.camera.getPickRay(movement.position)
        cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
        if (positions.length == 0) {
          positions.push(cartesian.clone())
        }
        // positions.pop();
        positions.push(cartesian)
        // 在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
          positions[positions.length - 1]
        )
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude)
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude)
        var heightString = cartographic.height
        tempPoints.push({
          lon:longitudeString,
          lat:latitudeString,
          hei:heightString
        })
        getHei.push(heightString)
        // 汇总所有高程
        maxHeight.push(heightString)
        adapCoordi=adapCoordi
        maxHeight=maxHeight
        _this.tempPoints=tempPoints
        // tempPoints.push(longitudeString)
        // tempPoints.push(latitudeString)
        // getHight(tempPoints)
        floatingPoint = viewer.entities.add({
          name: '多边形面积',
          position: positions[positions.length - 1],
          point: {
            pixelSize: 5,
            color: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.DEEPSKYBLUE,
            outlineWidth: 3
          }
        })
        measureFeature_polygon.push(  )
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
 
      handler.setInputAction(function (movement) {
        handler.destroy()
        positions.pop()
        var polyCenter = Cesium.BoundingSphere.fromPoints(positions).center
        var textArea = '挖方体积为：'+getTiji(tempPoints) + 'm³'
        const _label = viewer.entities.add({
          name: '多边形面积',
          position: polyCenter,
          // position: positions[positions.length - 1],
          label: {
            text: textArea,
            font: '16px sans-serif',
            fillColor: Cesium.Color.DARKORANGE,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
          }
        })
        measureFeature_polygon.push(_label)
        // 绘制范围按钮颜色变回默认

        _this.isChange3=false
        let floodArr = []
        tempPoints.forEach((item)=>{
          floodArr.push(item.hei)
        })
        floodArr.sort()
        // 求最大高程
        let targetHeight=floodArr[floodArr.length-1].toFixed(2)-0
        // 求最小高程
        let minFlood=floodArr[0].toFixed(2)-0
        _this.maxFlood=targetHeight
        _this.miniFlood=minFlood
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
 
      var radiansPerDegree = Math.PI / 180.0 // 角度转化为弧度(rad)
      var degreesPerRadian = 180.0 / Math.PI // 弧度转化为角度
 
      // 计算多边形面积
      function getArea(points) {
        var res = 0
        // 拆分三角曲面
        for (var i = 0; i < points.length - 2; i++) {
          var j = (i + 1) % points.length
          var k = (i + 2) % points.length
          var totalAngle = Angle(points[i], points[j], points[k])
 
          var dis_temp1 = distance(positions[i], positions[j])
          var dis_temp2 = distance(positions[j], positions[k])
          res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle))
          console.log(res)
        }
 
        return (res / 1000000.0).toFixed(4)
      }
      function logPosition (position) {
        var ray = viewer.camera.getPickRay(position)
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene)
        var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian)
        var long2 = Cesium.Math.toDegrees(cartographic.longitude)
        var lat2 = Cesium.Math.toDegrees(cartographic.latitude)
        console.log(long2 + ',' + lat2)
      }
 
      /* 角度 */
      function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1)
        var bearing23 = Bearing(p2, p3)
        var angle = bearing21 - bearing23
        if (angle < 0) {
          angle += 360
        }
        return angle
      }
      /* 方向 */
      function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree
        var lon1 = from.lon * radiansPerDegree
        var lat2 = to.lat * radiansPerDegree
        var lon2 = to.lon * radiansPerDegree
        var angle = -Math.atan2(
          Math.sin(lon1 - lon2) * Math.cos(lat2),
          Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        )
        if (angle < 0) {
          angle += Math.PI * 2.0
        }
        angle = angle * degreesPerRadian // 角度
        return angle
      }
 
      var PolygonPrimitive = (function () {
        function _(positions) {
          this.options = {
            name: '多边形',
            polygon: {
              hierarchy: [],
              // perPositionHeight : true,
              material: new Cesium.Color(153,102,0, 0.2)
              // material: Cesium.Color.GREEN.withAlpha(0.5)
              // heightReference:20000
            }
          }
 
          this.hierarchy = { positions }
          this._init()
        }
 
        _.prototype._init = function () {
          var _self = this
          var _update = function () {
            return _self.hierarchy
          }
          // 实时更新polygon.hierarchy
          this.options.polygon.hierarchy = new Cesium.CallbackProperty(
            _update,
            false
          )
          const _polygon = viewer.entities.add(this.options)
          _polygon=_polygon
          measureFeature_polygon.push(_polygon)
          this.measureFeature_polygon=measureFeature_polygon
          // console.log(this.measureFeature_polygon);
        }
 
        return _
      })()
 
      function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1)
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2)
        /** 根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic()
        geodesic.setEndPoints(point1cartographic, point2cartographic)
        var s = geodesic.surfaceDistance
        // 返回两点之间的距离
        s = Math.sqrt(
          Math.pow(s, 2) +
            Math.pow(point2cartographic.height - point1cartographic.height, 2)
        )
        return s
      }

      // 求体积
      function getTiji(points){
        let num = getHei.reduce((old, now) => {
            return old + now
        }, 0)
        // 最大高度
        let maxhei=Math.max(...getHei)
        let averDeep = num/getHei.length
        let mianji=getArea(points)*1000000
        console.log(mianji);
        let tiji = mianji*(_this.deep+maxhei-averDeep)
        return tiji
      }

    },

  },
}
</script>

<style scoped>
.measure-tools{
  position: absolute;
  top: 25vh;
  left: 6vw;
  background-color: rgba(0, 0, 0, .3);
  z-index: 999;
  color: #fff !important;
  height: 21vh;
  width: 16vw;
  border: 1px solid #60cdad;}
.title{
  font-size: 1.8vh;
  margin-top: 1vh;
  padding-bottom: 1vh;
  border-bottom: 1px solid #60cdad;
  box-sizing: border-box;
  color: #60cdad;
}
.measure{
  margin-top: 1vh;
  display: flex;
  justify-content: space-around;
  width: 100%;
  flex-wrap: wrap
}
.measure-item{
  /* display: flex; */
  font-size: 1.5vh;
  vertical-align: top;
  width: 30% !important;
  height: 3vh !important;
  margin-top: 2vh;
  cursor: pointer;
}
.iconfont {
  font-family: "iconfont" !important;
  /* font-size: 12px; */
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
#measure-icon{
  margin-right: 0.2vw !important;
}
#close-1{
  margin-left: 9vw;
  cursor: pointer
}
.measure-item:hover{
  color: #60cdad;
}
/* 挖方计算 */
.measure-tiji{
  position: absolute;
  top: 25vh;
  left: 6vw;
  border: 1px solid#60cdad;
  height: 18vh;
  width: 17vw;
  z-index: 999;
  background-color: rgba(0,0,0,.4);
  color: rgba(255,255,255,.9);
}
.tiji-top{
  margin-top: 1vh;
  padding-bottom: 1vh;
  border-bottom: 1px solid #60cdad;
}
#close-2{
  margin-left: 10vw;
  cursor: pointer;
}
.input-tiji{
  width: 3vw;
}
.tiji-bottom{
  margin-top: 2vh;
  font-size: 1.7vh;
  display: flex;
  padding-left: 1vw;
  flex-wrap: wrap;
}
.tiji-deep{
  margin-right: 1vw;

}
.tiji-draw:hover{
  color: #60cdad;
}
.tiji-draw{
  cursor: pointer;
}
</style>